<template>
  <div class="upload">
    <div class="notice_box">带*为必填项，请根据实际情况进行填写</div>
    <div v-for="(item, index) in material" class="uploader_box">
      <div>
        <van-cell>
          <!-- 使用 title 插槽来自定义标题 -->
          <template #title>
            <span v-if="item.must * 1 === 1" style="color: red">*</span>
            <span style="text-align: center">{{item.name}}</span>
          </template>
          <template #default>
            <div>
              <van-uploader
                v-model="item.imgUrl"
                accept="image/*"
                :after-read="afterRead(index)"
                :preview-image="false"
                multiple
              >
                
                <van-button size="small" plain hairline type="info">上传</van-button>
              </van-uploader>
            </div>
    
          </template>
        </van-cell>
        <div class="img-content" v-if="item.imgList && item.imgList.length > 0">
          <ul>
            <li v-for="(img, i) in item.imgList" :key="i">
              <div>
                <div @click="del(index, i)" class="del"><van-icon name="cross" /></div>
                <img @click="preview(index, i)" :src="img.imgData" alt="">
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="btn-content">
      <van-button type="info" block @click="submitForm">提交表单</van-button>
    </div>
  </div>
</template>

<script>
  import { apis } from "../request/apis";
  import { ImagePreview } from 'vant';

  export default {
    name: 'upload',
    data() {
      return {
        material: JSON.parse(sessionStorage.getItem('materials')),
        uid: '',
        itemBasicInfo: JSON.parse(sessionStorage.getItem('itemBasicInfo')),
        dataId: this.$route.query.dataId,
        info: JSON.parse(sessionStorage.getItem('formData')),
        mailInfo: JSON.parse(sessionStorage.getItem('postObj')),
        userInfo: this.$store.state.userInfo,
        windowsub: [],
        docid: '',
        objectType: this.$route.query.objectTypeCode,
        formId: this.$route.query.formId,
        userType: this.$store.state.userType,
      }
    },
    created() {
      this.getUcid()
    },
    methods: {
      async getUcid() {
        const params = {
          account: this.userInfo.username || this.userInfo.loginname,
          address: this.userInfo.address || this.userInfo.regaddress || '',
          cardNo: this.userInfo.cardId || this.userInfo.cardid || '',
          creditCode: '',
          email: this.userInfo.email || '',
          icregnumber: '',
          name: this.userInfo.name || '',
          orgName: this.itemBasicInfo.orgName || '',
          orgNo: '',
          phone: this.userInfo.phone || this.userInfo.mobile,
          sex: this.info.sex || '',
          type: this.userType + '1',
          userId: this.userInfo.uuid
        };
        apis.requestGetUid(params).then((res) => {
          if (res.success) {
            this.uid = res.data.uid
          }
        })
      },
      afterRead(index) {
        return (file) => {
          if (!Array.isArray(file)) {
            file = [file]
          }
          const material = [ ...this.material ];
          let params = new FormData();
          const fileObj = {};
          file.forEach((val) => {
            fileObj[val.file.name] = val;
            params.append('file', val.file);
          });
          apis.requestUploadify(params).then((res) => {
            if (res.success) {
              material[index].imgList = material[index].imgList || [];
              if (!Array.isArray(res.data)) {
                res.data = [res.data]
              }
              res.data.forEach((val) => {
                const imgObj = {
                  filePath: val.scc.docid,
                  fileName: val.url,
                  url: val.path,
                  type: '1',
                  operatorId: this.userInfo.userId,
                  operatorName: this.userInfo.username,
                  documentName: material[index].name,
                  documentId: material[index].code,
                  imgData: fileObj[val.url].content
                };
                material[index].imgList.push(imgObj)
              });
              this.material = material;
            }
          })
          
        }
      },
      del(index, imgIndex) {
        const { material } = this;
        material[index].imgList.splice(imgIndex, 1);
        this.material = [...material]
      },
      preview(index, imgIndex) {
        const { material } = this;
        const { imgList } = material[index];
        const imgUrlList = imgList.map((val) => {
          return val.imgData
        });
        ImagePreview({
          images: imgUrlList,
          startPosition: imgIndex,
          closeable: true,
        })
      },
      async submitForm() {
        // alert(this.userInfo)
        let metail = [];
        let ableSubmit = true;
        for (let i = 0; i < this.material.length; i++) {
          const val = this.material[i];
          val.imgList = val.imgList || [];
          metail = [...metail, ...val.imgList];
          if (val.must * 1 === 1) {
            if (!(val.imgList?.length > 0)) {
              this.$dialog.alert({
                title: '提示',
                message: '请先上传' + val.name,
              }).then(() => {});
              ableSubmit = false;
              break
            }
          }
        }
        if (!ableSubmit) {
          return
        }
        const windowsub = this.material.map(item => {
          if (!item.imgUrl) {
            return {
              name: item.name,
              code: item.code
            }
          }
        }).filter(item => item);
        let info = {};
        for (let k in this.info) {
          info[`info.${k}`] = this.info[k]
        }
        let params = {
          formId: this.formId,
          dataId: this.dataId,
          zjhm: this.userInfo.cardId || this.userInfo.cardid,
          sqrxm: this.userInfo.username || this.userInfo.name,
          lxrxm: this.userInfo.username || this.userInfo.name,
          lxrphone: this.userInfo.phone || this.userInfo.mobile,
          userName: this.userInfo.username || this.userInfo.loginname,
          ucid: this.uid,
          objectType: this.objectType,
          powerType: this.itemBasicInfo.type,
          powerSource: this.itemBasicInfo.powerSource,
          itemId: this.itemBasicInfo.itemId,
          itemCode: this.itemBasicInfo.itemCode,
          itemName: this.itemBasicInfo.itemName,
          orgCode: this.itemBasicInfo.orgCode,
          orgName: this.itemBasicInfo.orgName,
          regionCode: this.itemBasicInfo.regionCode,
          regionName: this.itemBasicInfo.regionName,
          receiveNum: '',
          formName: this.itemBasicInfo.formName,
          innerCode: '',
          assort: this.itemBasicInfo.assort,
          isOnlineYichuang: this.itemBasicInfo.isOnlineYichuang,
          transferred: '1',
          state: 'sp',
          ly: 'ASD',
          'servicelist.applicantName': this.userInfo.applicantName,
          'servicelist.applicantID': this.userInfo.applicantID,
          'servicelist.applicantMobile': this.userInfo.applicantMobile,
          'servicelist.applicantAddress': this.userInfo.applicantAddress,
          'mailInfo.jglqfs': this.mailInfo.code,
          'mailInfo.sjrxm': this.mailInfo.sjrxm,
          'mailInfo.sjrdh': this.mailInfo.sjrdh,
          'mailInfo.yzbm': this.mailInfo.yzbm,
          'mailInfo.sjdz': this.mailInfo.sjdz,
          ...info,
          'userInfo.userName': this.userInfo.username,
          'userInfo.mobile': this.userInfo.phone,
          'userInfo.no': this.userInfo.cardId
        };
        if (windowsub.length === 0) {
          params[`windowsub[0].code`] = '';
          params[`windowsub[0].name`] = ''
        } else {
          windowsub.map((item, index) => {
            params[`windowsub[${index}].code`] = item.code;
            params[`windowsub[${index}].name`] = item.name
          })
        }
        if(metail.length === 0){
          params[`metail[0].documentName`] = '';
          params[`metail[0].filePath`] = '';
          params[`metail[0].fileName`] = '';
          params[`metail[0].documentId`] = '';
          params[`metail[0].url`] = '';
          params[`metail[0].type`] = '';
          params[`metail[0].operatorId`] = '';
          params[`metail[0].operatorName`] = ''
        }else {
          metail.map((item, index) => {
            params[`metail[${index}].documentName`] = item.documentName;
            params[`metail[${index}].filePath`] = item.filePath;
            params[`metail[${index}].fileName`] = item.fileName;
            params[`metail[${index}].documentId`] = item.documentId;
            params[`metail[${index}].url`] = item.url;
            params[`metail[${index}].type`] = item.type;
            params[`metail[${index}].operatorId`] = item.operatorId;
            params[`metail[${index}].operatorName`] = item.operatorName
          })
        }
        apis.requestSubmitSP(params).then((res) => {
          if (res.success) {
            this.$router.push({
              path: '/success',
              query: {
                pageType: 'success'
              }
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .upload{
  }
  .btn-content{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 16px;
    background-color: white;
  }
  .notice_box {
    width: 100%;
    height: 30px;
    line-height: 30px;
    padding: 0 15px;
    font-size: 14px;
    background: #FCECED;
    color: #DF3C37;
  }
  .uploader_box{
    padding: 0 16px;
    >div{
      border-bottom: 1px solid #eeeeee;
      .van-cell{
        border: none;
        padding: 10px 0;
        .van-cell__title{
          flex: 1;
        }
        .van-cell__value{
          padding-left: 20px;
          flex: none;
          display: flex;
          align-items: center;
          .van-button{
            width: 60px;
          }
        }
        &:after{
          display: none;
        }
      }
      .img-content{
        ul{
          margin: 0 -5px;
          padding: 0;
          li{
            padding: 0 5px 10px;
            float: left;
            >div{
              width: 70px;
              height: 70px;
              border: 1px solid #eeeeee;
              /*padding: 5px;*/
              position: relative;
              overflow: hidden;
              .del{
                position: absolute;
                top: 0;
                right: 0;
                width: 20px;
                height: 20px;
                background-color: rgba(0, 0, 0, 0.7);
                border-radius: 0 0 0 12px;
                i{
                  color: white;
                  font-size: 12px;
                  display: block;
                  text-align: center;
                  line-height: 18px;
                }
              }
              img{
                display: block;
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }
          &:after{
            content: "";
            display: block;
            clear: both;
          }
        }
      }
      
    }
  }
  
  .van-uploader__preview-image {
    width: 2rem;
    height: 2rem;
  }
</style>
